package com.example.mystore.controller;

import com.example.mystore.model.User;
import com.example.mystore.model.Admin;
import com.example.mystore.service.UserService;
import com.example.mystore.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private AdminService adminService;

    // 用户登录
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody User user) {
        User authenticatedUser = userService.authenticate(user.getUsername(), user.getPassword());
        if (authenticatedUser != null) {
            // 检查是否为管理员
            Admin admin = adminService.findByUserId(authenticatedUser.getId());
            if (admin != null) {
                return ResponseEntity.ok().body("{\"type\": \"admin\"}");
            }
            // 普通用户
            return ResponseEntity.ok().body("{\"type\": \"user\", \"userId\": " + authenticatedUser.getId() + "}");
        } else {
            return ResponseEntity.status(401).body("登录失败：用户名或密码错误");
        }
    }

    // 用户注册
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User user) {
        User existingUser = userService.findByUsername(user.getUsername());
        if (existingUser != null) {
            return ResponseEntity.status(400).body("用户名已存在");
        }

        userService.save(user);
        return ResponseEntity.ok().body("注册成功");
    }
}
